from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import time
import pandas as pd

class Grap():
    def __init__(self):
        #设置驱动路径，selenium4之后的新写法
        self.service = Service(executable_path=r"C:\Program Files\Google\Chrome\Application\chromedriver.exe")
        # 实例化浏览器对象
        self.driver = webdriver.Chrome(service=self.service) 
        self.df = pd.DataFrame(columns=["id","title","score","star","year","duration", \
                                        "director","actors","vote"])
        self.df_save_path = "./data/nowplay.csv"
        self.sc_df = pd.DataFrame(columns=["rating","comment"])
        self.sc_save_path = "./data/short_comments.csv"
    
    def get_nowplaying(self):
        self.driver.get("https://movie.douban.com/cinema/nowplaying/leshan/")
        time.sleep(2)
        elements = self.driver.find_elements(By.XPATH,"//ul[@class='lists']/li[@class='list-item']")
        i = 0
        for ele in elements:
            did = ele.get_attribute("id")
            dtitle = ele.get_attribute("data-title")
            dscore = ele.get_attribute("data-score")
            dstar = ele.get_attribute("data-star")
            dyear = ele.get_attribute("data-release")
            ddura = ele.get_attribute("data-duration")
            ddirector = ele.get_attribute("data-director")
            dactors = ele.get_attribute("data-actors")
            dvote = ele.get_attribute("data-votecount")
            self.df.loc[i] = [did, dtitle, dscore, dstar, dyear, ddura, ddirector, dactors, dvote]
            i = i+1
        self.df.to_csv(self.df_save_path,index=None)
    
    def get_short_comment(self):
        self.driver.get("https://movie.douban.com/subject/36653918/comments?status=P")
        a = 0
        while(a<1000):
            elements1 = self.driver.find_elements(By.XPATH,"//span[@class='short']") #评论
            elements2 = self.driver.find_elements(By.XPATH, \
                                              "//span[@class='comment-info']/span[contains(@class,'rating')]")
            for ele1,ele2 in zip(elements1,elements2):
                comment = ele1.text
                rating = ele2.get_attribute("title")
                self.sc_df.loc[a] = [rating,comment]
                a = a+1
            
            next_ele = self.driver.find_elements(By.XPATH,"//div[@id='paginator']/a")
            try:
                link = next_ele[2].get_attribute("href")
                self.driver.get(link)
            except:
                break
        
        self.sc_df.to_csv(self.sc_save_path, index=None)



if __name__ == "__main__":
    g = Grap()
    g.get_short_comment() 